var serverData = {};
var	serverTable;

var serverData2 = {};
serverData2.key ='';
var	serverTable2;

var serverData1 = {};
serverData1.key="";
var serverTable1;

jQuery("#orderUnitArea").select2().trigger("change");

//引入客户信息弹窗	 
jQuery('#queryCustomer').on("click",function(){
	 jQuery("#queryCustomerModal").modal('show');
});

//销售机会登记
jQuery('#btnReg').on("click",function(){
	var url=window.rootPath+'/ui/expectedOrder/register';
	window.location = url;
});

jQuery('#btnCSave').on("click",function(){
	if (jQuery("#editForm") && !jQuery("#editForm").Validform({
		tiptype : 3,
		showAllError : true
	}).check(false)) {return;}
	jQuery("#btnCSave").attr("disabled","disabled");
	var api = window.rootPath + "/ui/expectedOrder/save2chance";
	var d={
			"orderId" : $("#orderId").val(),
			"chanceId" : $("#chanceId").val(),
			"orderUnitArea" : $("#orderUnitArea").val(),
			"orderUnit" : $("#orderUnit").val(),
			"name" : $("#name").val(),
			"deviceState" : $("#deviceState").val(),
			"chargePerson" : $("#chargePerson").val(),
			"probability" : $("#probability").val(),
			"orderAmount" : $("#orderAmount").val(),
			"amountMoney" : $("#amountMoney").val(),
			"expectedDate" : $("#expectedDate").val(),
			"explain" : $("#explain").val()
	};
	jQuery.ajax({
		type : 'post',
		url : api,
		data : JSON.stringify(d),
		dataType : 'json',
		contentType : 'application/json;charset=utf-8',
		success : function(data) {
			jQuery("#btnCSave").removeAttr("disabled");
			jQuery('#editModal').modal('hide');
			serverTable.draw();
		}
	});
});


jQuery('#pull-in').on("click",function(){
	 var selects=getSelect("#customerTable",5);
  	   if(selects.length>1){
  		   $.springLemonDialog({
  		         content: '只能操作一条记录',// 确认文本
  		         clickButton: function (sender, modal, index) {// 按钮事件处理
  		             $(this).closeDialog(modal);
  		         }
  		   }); 
  	   }
  	   else if(selects.length==0){
  		   $.springLemonDialog({
  		         content: '请选择要操作的记录',// 确认文本
  		         clickButton: function (sender, modal, index) {// 按钮事件处理
  		             $(this).closeDialog(modal);
  		         }
  		   }); 
  	   }else if(selects.length==1){
			jQuery("#orderUnit").val(selects[0].customerName);
			jQuery("#orderUnitArea").select2().val(selects[0].saleArea.superiorArea).trigger("change");
			jQuery("#queryCustomerModal").modal('hide');
  	   }
});

jQuery(document).ready(function () {

	   serverTable=  jQuery('#dataTable').DataTable({
        "serverSide": true,
        "ordering": false,
        "ajax": {
            "dataType": "json",
            "type": "get",
            "cache": false,
            "url": window.rootPath+'/ui/expectedOrder/getpage',
            "data": function (d) {
                return $.extend({}, d, serverData);
            }
        },
        columns: [
            {
            data: null,
            defaultContent: ""
            },
            {
    		    data:'eid',
    		    render: function(data, type, full, meta){
    		    	var operate ='<input type="checkbox" class="orders" data-id="'+data+'" >';
    		    	var id=data.id;
    		    	return operate;
    						
    				}
    	       },
           {
           	data: 'eorderAmount'
           },
           {
        	   	data: 'eamountMoney'
           },
           {
        	   data: 'echargePerson'
           },
           {
           	data: 'eprobability'
           },
           {
           	data: 'eexplain'
           },
           {
           	data: 'eexpectedDate',
           	render: function (data, type, full, meta) {
                    if (data)
                        return moment(data).format('YYYY/MM/DD');
                    else
                        return '';
                }
            },
            {
            	 data: 'cname'
            },
            {
            	data: 'cchancePriority'
            },
            {
            	data: 'cuserName'
            },
            {
            	data: 'cuserArea'
            },
            {
                data: 'csourceArea'
            },
            {
                data: 'corderUnit'
            },
            {
                data: 'corderAmount'
            },
            {
                data: 'cprojectState'
            },
            {
                data: 'cdeviceState'
            },
            {
                data: 'cbusiness'
            },
            {
                data: 'cdeviceState'
            },
            {
                data: 'cmemo'
            }
           
            ],
        "drawCallback": function ( oSettings ) {             
            var k = 0;
            var total = oSettings.aiDisplay.length + oSettings._iDisplayStart;

            for ( var i=oSettings._iDisplayStart, iLen=total ; i<iLen ; i++ )
            {
                $('td:eq(0)', oSettings.aoData[ oSettings.aiDisplay[k] ].nTr ).text( i+1 );
                k++;
            }
  
            serverTable.off('click','tr');
            serverTable.on( 'click', 'tr', function (event) {
                event=event||window.event;
                var target=event.target||event.scrElement;
                var data = serverTable.row( this ).data();

                return;
            } );
        }
        
    });
	   
    //导出
    jQuery('#orderEx').on('click', function() {
    		jQuery('#orderModal').modal('show');
	});
    
    //导出
    jQuery('#orderAnalysisEx').on('click', function() {
    		jQuery('#orderAnalysisModal').modal('show');
    });
    
    //编辑
    jQuery('#btnEdit').on('click', function() {
    		var obj = $('.orders:checked');
    		if(obj.length == 0){
    			alert("请选择预计订单！");
    		}else if(obj.length > 1){
    			alert("请选择一条预计订单！");
    		}else{
    			var orderId = obj.attr('data-id');
    			var url = window.rootPath+'/ui/expectedOrder/getOrder/'+orderId;
    			 jQuery.ajax({
    					url : encodeURI(url),
    					type : 'post',
    					data : '',
    					dataType : 'json',
    					contentType : 'application/json;charset=utf-8',
    					success : function(data) {
    						if(data.code == 0){
	    						var order = data.order;
	    						setOrderValue(order);
	    						jQuery('#editModal').modal('show');
    						}else{
    							alert(data.msg);
    						}
    					}
    				}); 
    		}
    		
    });
    
    //删除
    jQuery('#btnDel').on('click', function() {
	    	var obj = $('.orders:checked');
	    	if(obj.length == 0){
	    		alert("请选择预计订单！");
	    	}else{
	    		var json = new Array;
	    		obj.each(function(i){
	    			json[i] = $(this).attr('data-id');
	    		})
	    		var url = window.rootPath+'/ui/expectedOrder/deleteOrder';
	    		jQuery.ajax({
	    			url : encodeURI(url),
	    			type : 'post',
	    			data : '{"delIds":'+JSON.stringify(json)+'}',
	    			dataType : 'json',
	    			contentType : 'application/json;charset=utf-8',
	    			success : function(data) {
	    				serverTable.draw();
	    				alert(data.msg);
	    			}
	    		}); 
	    	}
    });
    
	function setOrderValue(data){
		//清空表单
		$('#editForm')[0].reset();
		
		$('#chanceId').val(data.chance.id);
		$('#orderUnitArea').select2().val(data.chance.orderUnitArea).trigger("change");
		$('#orderUnit').val(data.chance.orderUnit);
		$('#name').val(data.chance.name);
		$('#deviceState').val(data.chance.deviceState);
		
		$('#orderId').val(data.id);
		$('#chargePerson').val(data.chargePerson);
		$('#probability').val(data.probability);
		$('#orderAmount').val(data.orderAmount);
		$('#amountMoney').val(data.amountMoney);
		var expectedDate = data.expectedDate;
		if(expectedDate != ''){
			expectedDate = moment(expectedDate).format('YYYY-MM-DD')
		}
		$('#expectedDate').val(expectedDate);
		$('#explain').val(data.explain);
	}
    
	//导出细目
    jQuery('#orderToEx').on('click', function() {
	    	if (jQuery("#orderToExForm") && !jQuery("#orderToExForm").Validform({
	    		tiptype : 3,
	    		showAllError : true
	    	}).check(false)) {return;}
	    	var url = window.rootPath+'/ui/expectedOrder/export?begin='+$("#begin").val()+'&end='+$("#end").val();
	    	//window.location = url;
	    	$("#ifram").attr('src','');
	    	$("#ifram").attr('src',url);
    });
    
    //导出分析报表
    jQuery('#orderAnalysisToEx').on('click', function() {
	    	if (jQuery("#orderAnalysisToExForm") && !jQuery("#orderAnalysisToExForm").Validform({
	    		tiptype : 3,
	    		showAllError : true
	    	}).check(false)) {return;}
	    	var url = window.rootPath+'/ui/expectedOrder/exportAnalysis?month='+$("#month").val();
	    	//window.location = url;
	    	$("#ifram").attr('src','');
	    	$("#ifram").attr('src',url);
    });
    
	///////列表中的全选
    $("#checkAll").click(function(){
    		var check = $(this).prop("checked");
        $(".orders").prop("checked", check);
	});
	   
    //查询
    jQuery('#searchBtn').on('click', function() {
		serverData.key = jQuery('#keyword').val();
		serverTable.draw();
	});
	// 撤销查询
	jQuery('#resetBtn').on("click", function() {
		jQuery('#keyword').val('');
		serverData.key = '';
		serverTable.draw();
	});
	
	 serverTable1 = jQuery('#customerTable').DataTable({
         "serverSide": true,
         "ordering": false,
         "ajax": {
             "dataType": "json",
             "type": "get",
             "cache": false,
             "url":window.rootPath+ '/ui/customer/getpage',
             "data": function (d) {
                 return $.extend({}, d, serverData1);
             }
         },
         "iDisplayLength": 5,
         columns: [
             {
             data: null
             },
             {
             	data: 'customerName'
             },
             {
                 data: 'saleArea.areaName'
             },
             {
                 data: 'business'
             },
             {
                 data: 'superior'
             },
             {
             	data: null,
                 defaultContent: "",
                 render: function (data, type, full, meta) {
                     var operate =//'<button type="button" class="btn btn-sm btn-info editBtn" title="编辑"><i class="fa fa-pencil"></i></button>'
                                    '<input type="checkbox" class="checkCustomer">';
                     return operate;

                 }
                 
             } 
           ],
         "drawCallback": function (oSettings) {
             var k = 0;
             var total = oSettings.aiDisplay.length + oSettings._iDisplayStart;

             for (var i = oSettings._iDisplayStart, iLen = total; i < iLen; i++) {
                 $('td:eq(0)', oSettings.aoData[oSettings.aiDisplay[k]].nTr).text(i + 1);
                 k++;
             }

             serverTable1.off('click', 'tr');
             serverTable1.on('click', 'tr', function (event) {
                 event = event || window.event;
                 var target = event.target || event.scrElement;
                 var data = serverTable1.row(this).data();

                 return;
             });
         }
     });
 //搜索
	jQuery('#searchBtn1').on('click', function() {
		serverData1.key = jQuery('#keyword1').val();
		serverTable1.draw();
	})
	// 撤销查询
	jQuery('#resetBtn1').on("click", function() {
		jQuery('#keyword').val('');
		serverData1.key = '';
		serverTable1.draw();
	});
	
});